package cn.tedu.csmall.product.repo.impl;

import cn.tedu.csmall.product.pojo.vo.AttributeListVO;
import cn.tedu.csmall.product.repo.IAttributeRedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Repository
public class AttributeRedisRepositoryImpl implements IAttributeRedisRepository {

    @Autowired
    RedisTemplate<String, Serializable> redisTemplate;

    public AttributeRedisRepositoryImpl() {
        log.debug("创建处理缓存的数据访问对象: BrandRedisRepositoryImpl");
    }

    @Override
    public void save(List<AttributeListVO> list) {
        String key = ATTRIBUTE_ITEM_KEY;
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();
        for (AttributeListVO attribute : list) {
            ops.rightPush(key, attribute);
        }

    }

    @Override
    public Long deleteAll() {
        Set<Serializable> members = redisTemplate.opsForSet()
                                    .members(ATTRIBUTE_ITEM_KEYS_KEY);
        Set<String> keys = new HashSet<>();
        for (Serializable member : members) {
            keys.add((String) member);
        }
        keys.add(ATTRIBUTE_ITEM_KEY);
        keys.add(ATTRIBUTE_ITEM_KEY_PREFIX);
        return redisTemplate.delete(keys);
    }

    @Override
    public List<AttributeListVO> list() {
        Long start = 0L;
        Long end = -1L;
        return list(start, end);
    }

    @Override
    public List<AttributeListVO> list(Long start, Long end) {
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();
        String key = ATTRIBUTE_ITEM_KEY;
        List<Serializable> range = ops.range(key, start, end);
        List<AttributeListVO> list = new ArrayList<>();
        for (Serializable serializable : range) {
            list.add((AttributeListVO) serializable);
        }
        return list;
    }
}
